<template>
  <!-- header部分 -->
    <header>
        <p>商家信息</p>
    </header>

  <!-- 商家logo部分 -->
    <div class="business-logo">
        <img :src=business.businessImg>
    </div>

  <!-- 商家信息部分 -->
    <div class="business-info">
        <h1>{{business.businessName}}</h1>
        <p>&#165;{{business.starPrice}}起送 &#165;{{business.deliveryPrice}}配送</p>
        <p>{{business.businessExplain}}</p>
    </div>

  <!-- 食品列表部分 -->
    <ul class="food">
        <template v-for="item in foodList">
            <li>
                <div class="food-left">
                    <img :src=item.foodImg>
                    <div class="food-left-info">
                        <h3 class="foodName">{{item.foodName}}</h3>
                        <p>{{item.foodExplain}}</p>
                        <p class="price">&#165;{{item.foodPrice}}</p>
                    </div>
                </div>
                <div class="food-right">
                    <div>
                        <font-awesome-icon :class="item.quantity<=0?'hidden':''" @click="updateCart(item,-1)" :icon="['fas', 'minus-circle']" style="color: #0097EF;" />
                    </div>
                    <p>{{item.quantity<=0?"":item.quantity}}</p>
                    <div>
                        <font-awesome-icon @click="updateCart(item,1)" :icon="['fas', 'plus-circle']" style="color: #0097EF;" />
                    </div>
                </div>
            </li>
        </template>
    </ul>
  <!-- 购物车部分 -->
    <div class="cart">
        <div class="cart-left">
            <div class="cart-left-icon">
                <font-awesome-icon :icon="['fas', 'shopping-cart']" style="color: white;" />
                <div class="cart-left-icon-quantity" :style="totalQuantity>0?'background-color: red':'background-color:transparent'">{{totalQuantity>0?totalQuantity:''}}</div>
            </div>
            <div class="cart-left-info">
                <p class="allPrice">{{totalPrice>0?totalPrice:''}}&#165;</p>
                <p>另需配送费{{business.deliveryPrice}}元</p>
            </div>
        </div>
        <div class="cart-right" @click="goConfirm()">
            <div class="cart-right-item" >
                结算
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">

import {useRoute} from "vue-router";
import {computed,onMounted, watchEffect, ref} from "vue";
import {BusinessVO} from "../type/business";
import {FoodVO} from "../type/food.ts";
import {getBusinessAPI} from "../service/business.ts";
import {getFoodsAPI} from "../service/food.ts";
import {debounce} from "../utils/common.ts";
import {CartVO, UpdateCartRequestDTO} from "../type/cart.ts";
import {getCartAPI, updateCartAPI} from "../service/cart.ts";
import router from "../router";
import {userStore} from "../store/user.ts";
import {ElMessage} from "element-plus";
const user = userStore()
//商家信息
const  business = ref<BusinessVO>({
    id:0,
    businessName:"",
    businessAddress:"",
    businessExplain:"",
    businessImg:"",
    starPrice:0,
    deliveryPrice:0,
    quantity:0
});
const foodList = ref<FoodVO[]>([]);
//定义购物车列表
const cart = ref<CartVO>({
    id:0,
    userId:0,
    businessVO:null,
    totalQuantity:0,
    itemVOS:[]
});
//定义节流阀
const isRequest = ref(false)
const totalQuantity = ref(0);
const totalPrice = ref(0);
//请求实体
const updateDTO = ref<UpdateCartRequestDTO>({
    businessId:0,
    cartId:0,
    foodId:0,
    changeQuantity:0,
})
//定义获取购物车的方法
const getCart = async (id:number)=>{
    //判断用户是否登录
    if (user.loginUser && user.loginUser.id>0){
        const res = await  getCartAPI(id);
        if (res.data != null && res.data.id>0){
            cart.value = res.data;
            console.log(cart.value)
            //修改初始商品数量
            cart.value.itemVOS.forEach(cartItem => {
                // 找到 productList 中对应的商品
                let product = foodList.value.find(item => item.id === cartItem.food.id);
                if (product) {
                    // 更新商品的数量
                    product.quantity = product.initQuantity = cartItem.quantity;
                }
            });
        }
    }

}

// 使用 watchEffect 计算总价和总数量
watchEffect(() => {
    let quantity = 0;
    let price = 0;
    foodList.value.forEach(product => {
        quantity += product.quantity;
        price += product.quantity * product.foodPrice;
    });
    totalQuantity.value = quantity;
    totalPrice.value = price;
});

const route = useRoute()
const businessId = route.params.id as number
onMounted(async ()=>{
    //获取商家信息
    const res_bunsiness = await getBusinessAPI(businessId)
    business.value = res_bunsiness.data;

    //获取商品信息
    const res_food = await getFoodsAPI(businessId);
    foodList.value = res_food.data;
    for (let i = 0; i < foodList.value.length; i++) {
        //设置默认数量为0
        foodList.value[i].quantity = 0;
        foodList.value[i].initQuantity = 0;
    }

    //获取购物车
    await getCart(businessId);
})
//添加商品到购物车
const updateCart = (foodItem:FoodVO,changeQuantity:number) =>{
    foodItem.quantity =foodItem.quantity + changeQuantity
    debounceFunc(foodItem);
}
//请求更新购物车
const updateCartRequest = async (foodItem:FoodVO) =>{
    updateDTO.value.cartId = cart.value.id
    updateDTO.value.foodId = foodItem.id
    updateDTO.value.businessId = business.value.id
    updateDTO.value.changeQuantity = foodItem.quantity

    //判断用户是否登录
    if (user.loginUser && user.loginUser.id>0){
        const res = await updateCartAPI(updateDTO.value);
        if (res.data != null){
            cart.value.id = res.data.cartId
            console.log("更新成功,更新到了购物车:"+res.data.cartId)
        }else{
            console.log(res.message)
        }
    }
}
let debounceFunc = debounce(updateCartRequest, 500);

const goConfirm = () =>{
    //判断是否存在购物车
    if (cart.value.id>0){
        router.push({path:`/confirm/${businessId}`})
    }else {
        ElMessage.error("请先选择商品")
        return
    }
}

</script>

<style scoped>
/****************** header部分 ******************/
header{
    width: 100%;
    height: 12vw;
    background-color: #0097FF;
    color: #fff;
    font-size: 4.8vw;

    position: fixed;
    left: 0;
    top: 0;
    z-index: 1000;

    display: flex;
    justify-content: center;
    align-items: center;
}
/****************** 商家logo部分 ******************/
.business-logo{
    width: 100%;
    height: 35vw;
    /*使用上外边距避开header部分*/
    margin-top: 12vw;

    display: flex;
    justify-content: center;
    align-items: center;
}
.business-logo img{
    width: 40vw;
    height: 30vw;
    border-radius: 5px;
}
/****************** 商家信息部分 ******************/
.business-info{
    width: 100%;
    height: 20vw;

    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.business-info h1{
    font-size: 5vw;
    margin-bottom: 0;
}
.business-info p{
    font-size: 3vw;
    color: #666;
    margin-top: 1vw;
    margin-bottom: 0;
}
.food{
    width: 100%;
    /*使用下外边距避开footer部分*/
    margin-bottom: 14vw;
}
.food li{
    width: 100%;
    box-sizing: border-box;
    padding: 2.5vw;
    user-select: none;

    display: flex;
    justify-content: space-between;
    align-items: center;
}
.food-left{
    display: flex;
    align-items: center;
}
.food-left img{
    width: 20vw;
    height: 20vw;
}
.food-left .food-left-info{
    margin-left: 3vw;
}
.food-left .food-left-info h3{
    font-size: 3.8vw;
    color: #555;
    text-align: left;
}
.food-left .food-left-info p{
    font-size: 3vw;
    color: #888;
    margin-top: 2vw;
    text-align: left;
}
.food-right{
    width: 16vw;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.food-right .fa-minus-circle{
    font-size: 5.5vw;
    color: #999;
    cursor: pointer;
}
.food-right p{
    font-size: 3.6vw;
    color: #333;
}

.hidden{
    display: none;
    background-color: transparent;
}
/****************** 购物车部分 ******************/
.cart{
    width: 100%;
    height: 14vw;

    position: fixed;
    left: 0;
    bottom: 0;

    display: flex;
}
.cart .cart-left{
    flex: 2;
    background-color: #505051;
    display: flex;
}
.cart .cart-left .cart-left-icon{
    width: 16vw;
    height: 16vw;
    box-sizing: border-box;
    border: solid 1.6vw #444;
    border-radius: 8vw;
    background-color: #3190E8;
    font-size: 7vw;
    color: #fff;

    display: flex;
    justify-content: center;
    align-items: center;

    margin-top: -4vw;
    margin-left: 3vw;

    position: relative;
}
.cart .cart-left .cart-left-icon-quantity{
    width: 5vw;
    height: 5vw;
    border-radius: 2.5vw;
    background-color: red;
    color: #fff;
    font-size: 3.6vw;

    display: flex;
    justify-content: center;
    align-items: center;

    position: absolute;
    right: -1.5vw;
    top: -1.5vw;
}
.cart .cart-left .cart-left-info p:first-child{
    font-size: 4.5vw;
    color: #fff;
    margin-top: 1vw;
}
.cart .cart-left .cart-left-info p:last-child{
    font-size: 2.8vw;
    color: #AAA;
}
.cart .cart-right{
    flex: 1;
}
/*达到起送费时的样式*/
.cart .cart-right .cart-right-item{
    width: 100%;
    height: 100%;
    background-color: #38CA73;
    color: #fff;
    font-size: 4.5vw;
    font-weight: 700;
    user-select: none;
    cursor: pointer;

    display: flex;
    justify-content: center;
    align-items: center;
}
p{
    margin: 0;
}
.allPrice{
    text-align: left;
}
</style>
